package com.example.mapping.manage.visit;

import com.example.mapping.constant.Constants;
import com.example.mapping.entity.visit.JsonMappingVisitInfo;
import com.example.mapping.enumeration.VisitorTypeEnum;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 映射路径访问者
 *
 * @author baoyoujia
 * @date 2022/10/19
 */
@Component
public class JsonMappingAbsoluteVisitor implements Visitor {

    @Override
    public void visit(JsonMappingVisitInfo jsonMappingVisitInfo) {
        String mappingAbsolute = jsonMappingVisitInfo.getName();
        JsonNode objectNode = jsonMappingVisitInfo.getNode();
        String name = StringUtils.substringBefore(mappingAbsolute, Constants.Symbol.DOT);
        if (StringUtils.isEmpty(name)) {
            jsonMappingVisitInfo.addNodes(objectNode);
            return;
        }
        String suffixNodeName = StringUtils.substringAfter(mappingAbsolute, Constants.Symbol.DOT);
        jsonMappingVisitInfo.setName(suffixNodeName);
        if (objectNode.isArray()) {
            for (JsonNode node : objectNode) {
                JsonNode elementNode = node.get(name);
                if (Objects.nonNull(elementNode)) {
                    jsonMappingVisitInfo.setNode(elementNode);
                    jsonMappingVisitInfo.execute(this);
                }
            }
        }
        JsonNode node = objectNode.get(name);
        if (Objects.nonNull(node)) {
            jsonMappingVisitInfo.setNode(node);
            jsonMappingVisitInfo.execute(this);
        }
    }

    @Override
    public VisitorTypeEnum getType() {
        return VisitorTypeEnum.MAPPING_ABSOLUTE;
    }
}
